cmake_minimum_required(VERSION 3.22)
set(CMAKE_CXX_STANDARD 14)

set(CAPNPC_OUTPUT_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated)
set(CAPNPC_SRC_PREFFIX ${CMAKE_CURRENT_SOURCE_DIR})

# Generate Cap'n Proto C++ sources
#   The generated files create a library with the capn_{name} to link with.
#
#   @params proto_file list of proto files to generate
#   @params proto_lib_name name of the library to generate
#
function(generate_capn_proto)
    message("Generating Cap'n Proto C++ sources...")
    message("CAPNPC_OUTPUT_DIR: ${CAPNPC_OUTPUT_DIR}")
    message("CAPNPC_SRC_PREFFIX: ${CAPNPC_SRC_PREFFIX}")

    foreach (proto ${ARGN})

        set(proto_src_file ${proto}.capnp)
        set(proto_src ${CAPNPC_SRC_PREFFIX}/${proto_src_file})

        add_custom_command(
                OUTPUT ${CAPNPC_OUTPUT_DIR}/${proto}.capnp.c++ ${CAPNPC_OUTPUT_DIR}/${proto}.capnp.h
                COMMAND capnpc -oc++:${CAPNPC_OUTPUT_DIR} --src-prefix=${CAPNPC_SRC_PREFFIX} -I${CAPNPC_SRC_PREFFIX} ${proto_src}
                DEPENDS ${proto_src}
                COMMENT "Generating ${proto} Cap'n Proto C++ sources"
        )

        set(proto_lib_name capn_${proto})
        add_library(
                ${proto_lib_name}
                ${CAPNPC_OUTPUT_DIR}/${proto_src_file}.c++
        )

        target_include_directories(${proto_lib_name}
                PUBLIC ${CAPNPC_OUTPUT_DIR}
        )
    endforeach ()
endfunction()